from moviepy.editor import VideoFileClip, AudioFileClip
import speech_recognition as sr
import goslate
import pyttsx3
from pydub import AudioSegment
import os

def extract_audio(video_path, audio_path):
    video = VideoFileClip(video_path)
    audio = video.audio
    audio.write_audiofile(audio_path)

def transcribe_audio(audio_path):
    r = sr.Recognizer()
    with sr.AudioFile(audio_path) as source:
        audio = r.record(source)
        text = r.recognize_google(audio, language='en-US')
    return text

def translate_text(input_path, output_path):
    gs = goslate.Goslate()
    with open(input_path, 'r') as input_file, open(output_path, 'w') as output_file:
        for line in input_file:
            translation = gs.translate(line, 'zh')
            output_file.write(translation + '\n')

def speak_text(text, output_path):
    engine = pyttsx3.init()
    engine.setProperty('rate', 150)
    engine.setProperty('volume', 1)
    engine.setProperty('voice', 'zh')
    engine.save_to_file(text, output_path)
    engine.runAndWait()

def merge_audio_video(video_path, audio_path, output_path):
    video = VideoFileClip(video_path)
    audio = AudioFileClip(audio_path)
    video = video.set_audio(audio)
    video.write_videofile(output_path)

# 示例用法
video_path = "./folder/1-声明素材.mp4"
audio_path = "./folder/audio.wav"
output_path = "./folder/en_speech.txt"
translation_path = "./folder/output.txt"
output_audio_path = "./folder/output.mp3"
final_output_path = "./folder/output_with_audio.mp4"

extract_audio(video_path, audio_path)
transcription = transcribe_audio(audio_path)
print(transcription)
with open(output_path, 'w') as file:
    file.write(transcription)
translate_text(output_path, translation_path)
with open(translation_path, 'r') as file:
    text = file.read()
speak_text(text, output_audio_path)
merge_audio_video(video_path, output_audio_path, final_output_path)